package com.itheima.tliasmanagementspringboot.controller;

import com.itheima.tliasmanagementspringboot.common.R;
import com.itheima.tliasmanagementspringboot.pojo.Emp;
import com.itheima.tliasmanagementspringboot.service.EmpService;
import com.itheima.tliasmanagementspringboot.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录功能实现
 * 登录只是一个功能,是基于员工的一些业务,所以只需要对员工进行业务处理和数据访问即可
 */
@RestController
@Slf4j
@RequestMapping("/login")
public class LoginController {

    //依赖业务层对象
    @Autowired
    private EmpService empService;

    //员工信息里面有username和password,使用者也是员工,所以操作基本基于Emp对象
    @PostMapping
    public R login(@RequestBody Emp emp) {
        long startTime = System.currentTimeMillis();
        long endTime = 0;
        String typeName = LoginController.class.getTypeName();

        //各有优劣,Controller层写,避免了R在Service层的使用(对象侵入)
        //调用业务层：登录功能
        Emp empLogin = empService.loginOperationService(emp);
        //判断：登录用户是否存在
        if (empLogin.getUsername() == null) {
            endTime = System.currentTimeMillis();
            System.out.println(typeName + ", 请求路径为: " + "http://localhost:8080/login" + ", 耗时为: " + (endTime - startTime) + "ms" );
            return R.error("用户名错误");
        }else if (empLogin.getPassword() == null){
            endTime = System.currentTimeMillis();
            System.out.println(typeName + ", 请求路径为: " + "http://localhost:8080/login" + ", 耗时为: " + (endTime - startTime) + "ms" );
            return R.error("密码错误");
        }
        //自定义信息
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", empLogin.getId());
        claims.put("username", empLogin.getUsername());
        claims.put("name", empLogin.getName());
        //int i = 1 / 0;
        //使用JWT工具类，生成身份令牌
        //自定义部门是自己根据需求来决定的,所以需要传参)
        String token = JwtUtils.generateJwt(claims);
        endTime = System.currentTimeMillis();
        System.out.println(typeName + ", 请求路径为: " + "http://localhost:8080/login" + ", 耗时为: " + (endTime - startTime) + "ms" );
        log.info(typeName + ", 请求路径为: " + "http://localhost:8080/login" + ", 耗时为: " + (endTime - startTime) + "ms" );
        return R.ok(token);
    }
}
